<template>
  <div class="c-minh" :class="[theme, bg]">
    <template v-if="styleType == 1">
      <div :class="cssSupportSticky == false && isFixed ? 'tabHeight' : ''" style="visibility: hidden"></div>
      <div :class="[cssSupportSticky ? ($isWxApp() || unenableTopNav || isFaShou ? 'sticky c-wx-top0' : 'sticky') : isFixed ? 'fixed' : '', bg ? bg : 'c-bg-white']" class="c-w100 c-pz100">
        <my-small-tabbar :tabList="tabList" :tabIndex="tabIndex" :tabNameClass="fc ? 'c-fs24' : 'c-fs26'" :fontSet="fc ? {activeColor: fc, defaultColor: 'c-fc-E4A772'} : ''" :tbaIconBg="fc ? 'bg-brown' : 'theme-bg'" :flexClass="'c-justify-start'" :isScroll="true" :isSpreadMoney="true" @changeTab="changeTab" class="c-ph24" :class="inputBg"></my-small-tabbar>
        <div v-if="tabList && tabList.length > 0" class="c-fs22" :class="[fc ? fc : 'c-fc-xblack', bg ? bg : (isShowSearch ? 'c-bg-white' : 'c-bg-sgray'), (isShowSearch ? 'c-mb6' : '')]">
          <div class="c-flex-row c-aligni-center c-justify-sb c-fs24 c-w100" v-if="isShowSearch">
            <div class="c-ph24 c-pv16 c-w100">
              <div class="c-w100 c-hh56 c-br30 c-flex-row c-aligni-center" :class="inputBg">
                <span class="c-fs24 iconfont c-mh20" :class="fc ? fc : 'c-fc-gray'">&#xe6d6;</span>
                <input v-model="prodName" class="c-fs24 c-flex-grow1 c-bd0 c-hh50 c-lh50" :class="[inputBg, fc ? fc : 'c-fc-xblack']" type="text" ref="inputDom" @keyup.enter="clickSearch">
                <div @click="cancel" class="c-fs22 c-ph20 c-pr28 c-flex-shrink0" :class="fc ? fc : 'c-fc-sblack c-bd-l1-mgray'">取消</div>
              </div>
            </div>
          </div>
          <div class="c-pv24 c-flex-row c-justify-sb c-ph24" v-else>
            <div v-if="prodType == 999"></div>
            <div v-else class="c-flex-row c-aligni-center c-p">
              <div class="c-fs22 c-ww110">{{choosePrimary[0]}}</div>
              <popup-picker :data="chooseList" v-model="choosePrimary" value-text-align="left" class="c-ww110 c-pa c-p-t0 c-pz1 c-opacity0" @on-change="changeChoose" @on-show="showPicker" @on-hide="hidePicker"></popup-picker>
              <div class="iconfont c-fs14 c-pl8 c-pa c-p-r0 c-p-t8" :class="fc ? fc : 'c-fc-sgray'">{{arrow ? '&#xe6b0;' : '&#xe6b2;' }}</div>
            </div>
            <div class="c-flex-row c-aligni-center" @click="search">
              <div class="iconfont c-fs20">&#xe6d6;</div>
              <div class="c-pl10">搜索</div>
            </div>
          </div>
        </div>
      </div>
      <div class="minh800">
        <div class="c-ph24">
          <div class="c-flex-row c-pv20 c-bg-white c-mb20 c-br12 c-ph20" v-for="(item,index) in spreadList" :key="index" @click="clickDetail(item.prodType, item.prodId, item)">
            <div class="c-text-hidden c-flex-shrink0 c-p" :class="item.prodType == cfrom.vip || item.prodType == cfrom.svip ? 'c-ww180 c-maxh120' : item.prodType == cfrom.shopping ? 'c-ww160 c-hh160' : item.prodType == cfrom.ebooks ? 'c-ww160 c-hh240' : item.prodType == cfrom.activity ? 'c-ww180 c-hh90' : 'c-ww180 c-hh120'">
              <vip-custom-img :cover="item.cover" :imgClass="'imgCloseBig c-br12 c-maxh120'" :fontClass="{
                boxStyle: 'c-pv20 c-pl12',
                name: 'c-fs24 c-text-ellipsis1 c-fw-b',
                duration: 'c-fs18'}" :content="{name: item.name, duration: item.duration, durationType: item.durationType}" v-if="item.prodType == cfrom.vip || item.prodType == cfrom.svip" />
              <CoverImg v-else :coverSizeClass="'c-w100 c-h c-br12 c-text-hidden'" :coverUrl="item.cover.replace(/^\s*|\s*$/g, '')" :prodType="item.prodType" />
              <!-- <img :src="$addXossFilter(item.cover.replace(/^\s*|\s*$/g, ''), require('@/assets/defult270.png'))" v-else class="c-w100 c-h c-br12"/> -->
              <div v-if="prodType == 999" class="c-br8 c-hh26 c-lh28 c-ph6 c-textAlign-c c-translucent-balck60 c-fs18 c-fc-white c-pa c-p-b8 c-p-r8">{{item.prodType == 5 ? courseType[item.childType] : prodMapType[item.prodType]}}</div>
            </div>
            <div class="c-pl20 c-flex-column c-justify-sb c-flex-grow1 c-w0">
              <span class="c-fs26 c-text-ellipsis2 c-fw-b">{{item.name}}</span>
              <span class="c-fc-gray c-fs22 c-pt10">{{'￥' | iosPriceFilter}}{{prodType == cfrom.shopping || prodType == cfrom.activity ? countPrice(item) : item.price}}</span>
              <div class="c-flex-row c-justify-sb c-aligni-center c-pt2">
                <span class="c-fc-xmlred c-fs26"><span class="c-fs20">预计奖励:</span>{{'￥' | iosPriceFilter}}{{countIncome(item)}}<span class="c-fs20" v-if="item.range && Number(item.commonRaito) > 0">起</span></span>
                <div class="c-flex-row c-flex-center c-hh48 c-fc-white c-ph36 c-fs22 c-br32 c-ws-n" :class=" fc ? 'bgColor' : 'theme-bg'" @click.stop="goSpreadInvite(index, item.prodType)">分享</div>
              </div>
            </div>
          </div>
          <loading-status-tem :noDataText="'暂无数据'" :dataStatus="dataStatus"></loading-status-tem>
        </div>
      </div>
    </template>
    <template v-else-if="styleType == 2">
      <new-search-bar :searchText="prodName" @search="clickSearch" @cancel="clickSearch"></new-search-bar>
      <div :class="cssSupportSticky == false && isFixed ? 'tabHeight' : ''" style="visibility: hidden"></div>
      <div :class="[cssSupportSticky ? ($isWxApp() || unenableTopNav || isFaShou ? 'sticky c-wx-top0' : 'sticky') : isFixed ? 'fixed' : 'c-pf', bg ? bg : 'c-bg-white']" class="c-w100 c-pz100">
        <my-small-tabbar :tabList="tabList" :tabNameActiveStyle="'font-weight: 600'" :tabIndex="tabIndex" :tabNameClass="fc ? 'c-fs24' : 'c-fs26'" :fontSet="fc ? {activeColor: fc, defaultColor: 'c-fc-E4A772'} : ''" :tbaIconBg="fc ? 'bg-brown' : 'theme-bg'" :flexClass="'c-justify-start'" :isScroll="true" :isSpreadMoney="true" @changeTab="changeTab" class="c-pl24 pr90"></my-small-tabbar>
        <div class="c-ww90 c-hh76 c-pa c-p-r0 c-p-t0 c-flex-row c-flex-center">
          <div class="c-ww90 c-hh76 c-p-l0 c-p-r0 c-pl10 pop-price-bg">
            <div class="c-flex-row c-flex-center c-h c-bg-white">
              <div class="c-fs22 theme-fc">{{choosePrimary[0]}}</div>
              <popup-picker :data="chooseList" v-model="choosePrimary" value-text-align="left" class="c-w100 c-h100 c-pa c-p-t0 c-p-l0 c-pz1 c-opacity0" @on-change="changeChoose" @on-show="showPicker" @on-hide="hidePicker"></popup-picker>
              <div class="iconfont c-fs14 theme-fc">{{arrow ? '&#xe712;' : '&#xe714;' }}</div>
            </div>
          </div>
        </div>
        <!-- <div v-if="tabList && tabList.length > 0" class="c-fs22" :class="[fc ? fc : 'c-fc-xblack', bg ? bg : (isShowSearch ? 'c-bg-white' : 'c-bg-sgray'), (isShowSearch ? 'c-mb6' : '')]">
          <div class="c-pv24 c-flex-row c-justify-sb c-ph24">
            <div v-if="prodType == 999"></div>
            <div v-else class="c-flex-row c-aligni-center c-p">
              <div class="c-fs22 c-ww110">{{choosePrimary[0]}}</div>
              <popup-picker :data="chooseList" v-model="choosePrimary" value-text-align="left" class="c-ww110 c-pa c-p-t0 c-pz1 c-opacity0" @on-change="changeChoose" @on-show="showPicker" @on-hide="hidePicker"></popup-picker>
              <div class="iconfont c-fs14 c-pl8 c-pa c-p-r0 c-p-t8" :class="fc ? fc : 'c-fc-sgray'">{{arrow ? '&#xe6b0;' : '&#xe6b2;' }}</div>
            </div>
          </div>
        </div> -->
      </div>
      <div class="minh800">
        <div class="c-ph24 c-pt20">
          <div class="c-flex-row c-pv20 c-bg-white c-mb20 c-br12 c-ph20" v-for="(item,index) in spreadList" :key="index" @click="clickDetail(item.prodType, item.prodId, item)">
            <div class="c-text-hidden c-flex-shrink0 c-p" :class="item.prodType == cfrom.vip || item.prodType == cfrom.svip ? 'c-ww180 c-maxh120' : item.prodType == cfrom.shopping ? 'c-ww160 c-hh160' : item.prodType == cfrom.ebooks ? 'c-ww160 c-hh240' : item.prodType == cfrom.activity ? 'c-ww180 c-hh90' : 'c-ww180 c-hh120'">
              <vip-custom-img :cover="item.cover" :imgClass="'imgCloseBig c-br12 c-maxh120'" :fontClass="{
                boxStyle: 'c-pv20 c-pl12',
                name: 'c-fs24 c-text-ellipsis1 c-fw-b',
                duration: 'c-fs18'}" :content="{name: item.name, duration: item.duration, durationType: item.durationType}" v-if="item.prodType == cfrom.vip || item.prodType == cfrom.svip" />
              <CoverImg v-else :coverSizeClass="'c-w100 c-h c-br12 c-text-hidden'" :coverUrl="item.cover.replace(/^\s*|\s*$/g, '')" :prodType="item.prodType" />
              <!-- <img :src="$addXossFilter(item.cover.replace(/^\s*|\s*$/g, ''), require('@/assets/defult270.png'))" v-else class="c-w100 c-h c-br12"/> -->
              <div v-if="prodType == 999" class="c-br8 c-hh26 c-lh28 c-ph6 c-textAlign-c c-translucent-balck60 c-fs18 c-fc-white c-pa c-p-b8 c-p-r8">{{item.prodType == 5 ? courseType[item.childType] : prodMapType[item.prodType]}}</div>
            </div>
            <div class="c-pl20 c-flex-column c-justify-sb c-flex-grow1 c-w0">
              <span class="c-fs26 c-text-ellipsis2 c-fw-b">{{item.name}}</span>
              <span class="c-fc-gray c-fs22 c-pt10">{{'￥' | iosPriceFilter}}{{prodType == cfrom.shopping || prodType == cfrom.activity ? countPrice(item) : item.price}}</span>
              <div class="c-flex-row c-justify-sb c-aligni-center c-pt2">
                <span class="c-fc-xmlred c-fs26"><span class="c-fs20">预计奖励:</span>{{'￥' | iosPriceFilter}}{{countIncome(item)}}<span class="c-fs20" v-if="item.range && Number(item.commonRaito) > 0">起</span></span>
                <div class="c-flex-row c-flex-center c-hh48 c-fc-white c-ph36 c-fs22 c-br32 c-ws-n" :class=" fc ? 'bgColor' : 'theme-bg'" @click.stop="goSpreadInvite(index, item.prodType)">分享</div>
              </div>
            </div>
          </div>
          <loading-status-tem :noDataText="'暂无数据'" :dataStatus="dataStatus"></loading-status-tem>
        </div>
      </div>
    </template>
  </div>
</template>

<script>
import loadingStatusTem from "@/components/templates/common/loadingStatusTem.vue";
import MySmallTabbar from "@/components/templates/common/MySmallTabbar.vue";
import VipCustomImg from "@/components/templates/common/VipCustomImg.vue";
import CoverImg from '@/components/templates/common/coverImg.vue';
import newSearchBar from "@/components/templates/common/newSearchBar.vue"
import { PopupPicker } from 'ckjrweb-mp-ui/src/components/index';
import { goDetails } from "@/utils/goDetails.js";
import { utilJs } from "@/utils/common.js";
let pageIndex = 1;
const LIMIT = 10;
export default {
  name: "SpreadMoneyTemp",
  components: {
    loadingStatusTem,
    PopupPicker,
    MySmallTabbar,
    VipCustomImg,
    CoverImg,
    newSearchBar
  },
  props: {
    bg: {
      type: String,
      default: ''
    },
    fc: {
      type: String,
      default: ''
    },
    inputBg: {
      type: String,
      default: 'c-bg-f5'
    },
    styleType: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      theme: localStorage.getItem("colorName") ? localStorage.getItem("colorName") : 'mb5_default',
      prodType: 110,
      dataStatus: "HAS_MORE_DATA", //显示加载更多LOAD_MORE 加载中 LOADING 没有更多 NO_MORE_DATA
      spreadList: [],
      arrow: false, //箭头方向
      prodName: "",
      isShowSearch: false,
      isFixed: false, //是否吸顶
      cssSupportSticky: false,
      chooseList: [['价格', '默认']],
      choosePrimary: ['默认'],
      chooseType: 2, // 1：根据价格排序，2：根据商品排序, 默认商品排序
      tabList: [],
      tabIndex: 0,
      cfrom: global.ckFrom,
      isSearch: false, //是否搜索过
      companyAuth: JSON.parse(localStorage.getItem("companyAuth")),
      prodMapType: global.prodMapType,
      courseType: {
        0: '视频',
        1: '音频',
        2: '图文'
      },
      isFaShou: localStorage.getItem('isFaShou') == 1,
    };
  },
  created() {},
  computed: {
    // 判断是否有顶部导航
    unenableTopNav() {
      return this.companyAuth && this.companyAuth.companyTopNav && this.companyAuth.companyTopNav.style && this.companyAuth.companyTopNav.style == 5
    },
  },
  mounted() {
    if ((window.CSS && window.CSS.supports) || window.supportsCSS) {
      // 该方法可以判断不同内核的兼容性,较为准确
      this.cssSupportSticky = CSS.supports("(position: sticky) or (position: -webkit-sticky)");
    } else {
      // 自定义方法虽然能判断样式是否兼容，无法判断不同内核是否可以使用
      this.cssSupportSticky = this.cssSupport('position', 'sticky');
    }
    if (utilJs.checkNeedInitData(this.spreadList)) {
      this.initData()
    }
    window.addEventListener('scroll', this.windowScroll);
    window.addEventListener('scroll', this.windowScrollFunction);
  },
  watch: {
    $route(to, from) {
      if (from.path == "/") {
        this.initData();
      }
    }
  },
  methods: {
    // 判断样式是否被兼容
    cssSupport: function (attr, value) {
      let element = document.createElement('div');
      if (attr in element.style) {
        element.style[attr] = value;
        return element.style[attr] === value;
      } else {
        return false;
      }
    },
    changeTab(index, moveDir, prodType) {
      if (this.dataStatus == 'LOADING') {
        return
      }
      this.prodName = '';
      this.tabIndex = index;
      this.prodType = prodType;
      if (this.isFixed) {
        let height = this.$refs.bg ? this.$refs.bg.offsetHeight : 0;
        window.scrollTo(0, height);
      }
      this.reGetData();
    },
    goSpreadInvite(index, prodType) {
      if (prodType == 59) {
        this.$routerGo(this, "push", {
          path: `/homePage/spread/spreadAgent?&ckFrom=1`,
        });
      } else {
        let courseType = this.prodType == 110 ? 0 : this.prodType == 111 ? 1 : this.prodType == 112 ? 2 : '';
        this.$routerGo(this, "push", {
          path: "/homePage/spread/spreadCustom",
          query: { cId: this.spreadList[index].prodId, extId: this.spreadList[index].prodId, ckFrom: prodType, promote: 1, courseType: courseType }
        });
      }
    },
    countPrice(item) {
      return item.range ? (item.minPrice == item.maxPrice ? `${item.minPrice}` : `${item.minPrice} ~ ${item.maxPrice}`) : `${item.minPrice}`
    },
    countIncome(item) {
      let inCome = (Math.floor((item.price * item.commonRaito * 0.01) * 100) / 100).toFixed(2)
      return inCome / 1000 >= 1 ? Math.trunc(inCome) : inCome
    },
    search() {
      this.isShowSearch = true;
      this.$nextTick(() => {
        this.$refs.inputDom.focus()
      })
    },
    cancel() {
      if (this.isSearch) {
        this.prodName = '';
        this.isSearch = false;
        this.isShowSearch = false;
        this.reGetData();
      } else {
        this.prodName = '';
        this.isShowSearch = false;
      }
    },
    clickSearch(e) {
      this.isSearch = true;
      this.prodName = e.searchValue;
      this.reGetData();
    },
    // getTab() {
    //   utilJs.getMethod(`${global.apiurl}promote/promoteTitle`, res => {
    //     if (res.length > 0) {
    //       this.tabList = res.filter(item => {
    //         return item.show == 1;
    //       });
    //       this.prodType = this.tabList[0].prodType;
    //       this.getList();
    //     }
    //   })
    // },
    getTabs() {
      utilJs.getMethod(`${global.apiurl}promote/promoteTabConfig`, res => {
        if (res.tab && res.tab.length > 0) {
          this.tabList = res.tab.filter(item => {
            return item.enableShow == 1 && item.enableDredge == 1;
          });
          this.tabList.forEach((item) => {
            item.title = item.name;
          })
        }
        if (res.enableShowGoods == 1) {
          let centerProdItem = [{
            enableShow: 1,
            name: '主推商品',
            title: '主推商品',
            prodType: 999, //999：自定义主推商品
          }]
          this.tabList = [...centerProdItem, ...this.tabList]
        }

        // 如果是发售版本--只显示约课
        if (this.isFaShou) {

          const temp = this.tabList.find(item => item.prodType == 53)
          temp.sort = 0
          this.tabList = [temp]
        }
        if (this.tabList && this.tabList.length > 0) {
          this.prodType = this.tabList[0].prodType;
          this.getList();
        }
      })
    },
    //获取列表
    getList(onetime) {
      if (this.dataStatus == 'LOADING') {
        return
      }
      this.dataStatus = 'LOADING';
      let getUrl = '';
      if (this.prodType == 999) {
        if (this.styleType == 2) {
          this.chooseList = [['默认']];
          this.choosePrimary = ['默认'];
          this.chooseType = 2;
        }
        getUrl = `${global.apiurl}promote/list?isPromote=1&prodName=${this.prodName}&order=${this.chooseType}&limit=${LIMIT}&page=${pageIndex}`;
      } else {
        if (this.styleType == 2) {
          this.chooseList = [['价格', '默认']];
        }
        getUrl = `${global.apiurl}promote/list?prodType=${this.prodType}&prodName=${this.prodName}&order=${this.chooseType}&limit=${LIMIT}&page=${pageIndex}`;
      }
      utilJs.getMethod(getUrl, res => {
        if (pageIndex == 1) {
          this.spreadList = res.data
        } else {
          this.spreadList = [...this.spreadList, ...res.data]
        }
        if (res.data && res.data.length < LIMIT) {
          this.dataStatus = pageIndex == 1 && res.data.length == 0 ? 'NO_DATA' : 'NO_MORE_DATA';
        } else {
          this.dataStatus = "HAS_MORE_DATA";
          pageIndex++;
        }
      }, failRes => {
        this.dataStatus = 'DATA_ERROR';
      })
    },
    clickDetail(type, prodId, item) {
      if (this.prodType == 59) {
        this.$routerGo(this, "push", {
          path: "/homePage/agent/agentDesc",
          query: { applyType: item.vipType }
        });
      } else {
        let courseType = this.prodType == 999 && item.prodType == 5 ? item.childType : this.prodType == 110 ? 0 : this.prodType == 111 ? 1 : this.prodType == 112 ? 2 : '';
        goDetails(this, type, prodId, '', courseType);
      }
    },
    changeChoose(val) {
      if (this.isFixed) {
        let height = this.$refs.bg ? this.$refs.bg.offsetHeight : 0;
        window.scrollTo(0, height);
      }
      if (val[0] == '默认') {
        this.chooseType = 2;
      } else {
        this.chooseType = 1;
      }
      // this.arrow = !this.arrow;
      this.reGetData();
    },
    showPicker() {
      this.arrow = true;
    },
    hidePicker() {
      this.arrow = false;
    },
    reGetData() {
      pageIndex = 1;
      this.dataStatus = "HAS_MORE_DATA";
      this.spreadList = [];
      this.getList();
    },
    initData() {
      this.prodName = "";
      this.choosePrimary = ['默认'];
      pageIndex = 1;
      this.prodType = 5;
      this.chooseType = 2;
      this.tabList = [];
      this.tabIndex = 0;
      this.spreadList = [];
      this.dataStatus = "HAS_MORE_DATA";
      this.isSearch = false;
      this.isFixed = false;
      this.arrow = false;
      this.isShowSearch = false;
      // this.getTab();
      this.getTabs();
    },
    windowScroll() {
      let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
      if (scrollTop > 220) {
        this.isFixed = true;
      } else {
        this.isFixed = false;
      }
    },
    windowScrollFunction() {
      utilJs.handleLoading(() => {
        if (this.dataStatus == 'HAS_MORE_DATA' && this.spreadList.length > 0) {
          this.getList();
        }
      })
    },
  },
  destroyed() {
    window.removeEventListener('scroll', this.windowScroll);
    window.removeEventListener('scroll', this.windowScrollFunction);
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.c-lhnor {
  line-height: normal;
}
.bg {
  background-image: url("../../assets/i/wap/spread/bg.png");
  background-repeat: no-repeat;
  background-size: contain;
}
.hand {
  background: url("../../assets/i/wap/spread/hand.png") no-repeat;
  background-size: contain;
}
.mt-140 {
  margin-top: -3.5rem;
}
.sticky {
  position: sticky;
  position: -webkit-sticky;
  top: 1.4rem;
}
.fixed {
  position: fixed;
  width: 100%;
  top: 0;
}
.minh800{min-height: 20rem;}
.vux-cell-box >>> .vux-cell-value {
  color: #333;
}
.search-bg {
  background: #f5f5f5;
}
.maxh125 {max-height:  3.125rem;}

.bgColor {
  background-image: linear-gradient(90deg, #FF300C 0%, #ff300cb3 100%);
}
.pop-price-bg {
  background: linear-gradient(90deg, #00000000 4%, #000000 100%) no-repeat;
  background-size: 100% 90%;
  background-position-y: 2px;
}
.pr90 {
  padding-right:2.25rem;
}
</style>
